/*
-------------------------------------------------

	Channel.cpp

	Dmitriy Kuzmenko (Dgut)

-------------------------------------------------
*/

#include "Channel.h"
#include "Sound.h"

#ifdef WIN32
#include <windows.h>
#include <stdio.h>
#endif

namespace Autumn
{

Channel::Channel( ALuint id ) :
	id	( id )
{
}

Channel::~Channel( void )
{
	alSourceStop( id );
	alDeleteSources( 1, &id );
}

void Channel::Play( const Sound * sound )
{
//	Stop();
	alSourcei( id, AL_BUFFER, sound->GetID() );
	alSourcePlay( id );
}

void Channel::Play( Stream * stream )
{
	const ALuint STATE = GetState();

	if( STATE == AL_INITIAL )
	{
		for( int i = 0; i < STREAM_NUM_BUFFERS; i++ )
		{
			const ALuint ID = stream->GetNextChunk();
			alSourceQueueBuffers( id, 1, &ID );
		}

		alSourcePlay( id );
	}
	else	
	{
		ALint processed;
		alGetSourcei( id, AL_BUFFERS_PROCESSED, &processed );

		while( processed-- )
		{
			ALuint bid;
			alSourceUnqueueBuffers( id, 1, &bid );
			bid = stream->GetNextChunk();
			alSourceQueueBuffers( id, 1, &bid );
		}

		if( STATE == AL_STOPPED )
			alSourcePlay( id );
	}
}

/*void Channel::Pause( void )
{
	if( GetState() == AL_PLAYING )
		alSourcePause( id );
}

void Channel::Continue( void )
{
	if( GetState() == AL_PAUSED )
		alSourcePlay( id );
}*/

void Channel::Stop( void )
{
	alSourceStop( id );
	alSourcei( id, AL_BUFFER, 0 );
	alDeleteSources( 1, &id );
	alGenSources( 1, &id );
}

/*void Channel::SetVolume( float volume )
{
	alSourcef( id, AL_GAIN, volume );
}*/

/*void Channel::SetLoop( bool loop )
{
	alSourcei( id, AL_LOOPING, loop );
}*/

const ALint Channel::GetState( void ) const
{
	ALint state;
	alGetSourcei( id, AL_SOURCE_STATE, &state );
	return state;
}

const bool Channel::IsFree( void ) const
{
	const ALint state = GetState();
	return state != AL_PLAYING && state != AL_PAUSED;
}

Channel * const	Channel::Create( void )
{
	ALuint id = 0;
	alGenSources( 1, &id );
	return id ? new Channel( id ) : 0;
}

}	// namespace Autumn